package org.lee.jfc.bar;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;

/**
 * BarchartDemo
 * 条形图
 *
 * @author dralee
 * @date 2021-12-29 15:22:10
 **/
public class BarchartDemo extends JFrame {
    public BarchartDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        CategoryDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        chartPanel.setBackground(Color.white);
        add(chartPanel);

        pack();
        setTitle("Line chart");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JFreeChart createChart(CategoryDataset dataset) {
        JFreeChart chart = ChartFactory.createBarChart("Olympic gold medals in London",
                "", "Gold medals", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        chart.getLegend().setFrame(BlockBorder.NONE);
        //chart.setTitle(new TextTitle("Oily gold medals in London", new Font("Serif", Font.BOLD, 18)));
        return chart;
    }

    private CategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.setValue(46, "Gold medals", "USA");
        dataset.setValue(38, "Gold medals", "China");
        dataset.setValue(29, "Gold medals", "UK");
        dataset.setValue(22, "Gold medals", "Russia");
        dataset.setValue(13, "Gold medals", "South Korea");
        dataset.setValue(11, "Gold medals", "Germany");
        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new BarchartDemo().setVisible(true));
    }
}
